package com.crocodileq.interceptor;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.crocodileq.dto.UserDTO;
import com.crocodileq.utils.RedisConstants;
import com.crocodileq.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/***
 * @Author 鳄鱼杆
 * @Date 2025/9/10 18:30
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取token
        String token = request.getHeader("authorization");

        //判断token是否存在
        if(StrUtil.isBlank(token)){
            return true;
        }
        //2、查询redis用户
        String key = RedisConstants.LOGIN_USER_KEY + token;

        Map<Object, Object> userMap = stringRedisTemplate.opsForHash()
                .entries(RedisConstants.LOGIN_USER_KEY + token);
        //3、判断用户是否存在，不存在，拦截
        if(userMap.isEmpty()){
            return true;
        }

        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        //4、保存到ThreadLocal中
        UserHolder.saveUser(userDTO);

        //5、刷新token有效期
        stringRedisTemplate.expire(
                key,
                RedisConstants.LOGIN_USER_TTL,
                TimeUnit.MINUTES);


        //5、放行
        return true;
    }
}
